from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from PIL import Image
import pytesseract
import cv2
import numpy as np
import re

# 初始化Chrome浏览器
driver = webdriver.Edge()

# 打开指定的网页
driver.get("https://cas.shengda.edu.cn/lyuapServer/login?service=http://shengda.fysso.chaoxing.com/sso/shengda")

# 设置显式等待
wait = WebDriverWait(driver, 10)

try:
    # 等待账户输入框出现
    account_input = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/span/div[3]/div/div/div[1]/div/div/form/div[1]/div/div/span/span/input')))
    account_input.send_keys("202405930226")
    time.sleep(1)
    # 等待密码输入框出现并输入密码
    password_input = wait.until(EC.presence_of_element_located((By.ID, 'password')))
    password_input.send_keys("KKbjbzbj.3")
    time.sleep(1)
    print("输入结束")

    # 等待验证码图片元素出现并截取验证码图片
    captcha_image = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="root"]/span/div[3]/div/div/div[1]/div/div/form/div[4]/div/div/span/div/div[2]/div/img')))
    captcha_image.screenshot('captcha.png')

    # 读取图像
    image = cv2.imread('captcha.png')

    # 转换为灰度图
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 使用自适应阈值进行二值化
    binary_image = cv2.adaptiveThreshold(gray_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                        cv2.THRESH_BINARY, 11, 2)

    # 去噪（如果需要）
    binary_image = cv2.medianBlur(binary_image, 3)

    # 形态学操作（如果需要）
    kernel = np.ones((1, 1), np.uint8)
    binary_image = cv2.dilate(binary_image, kernel, iterations=1)

    # 使用 pytesseract 进行 OCR 识别
    captcha_text = pytesseract.image_to_string(binary_image, config='--psm 7 --oem 1 -c tessedit_char_whitelist=0123456789*+=')

    # 打印识别结果
    print("识别出的文本:", captcha_text)

    # 使用正则表达式提取数学表达式
    math_expression = re.search(r'(\d+)\s*([*×+])\s*(\d+)', captcha_text)

    if math_expression:
        # 提取数字并计算结果
        num1, operator, num2 = math_expression.groups()
        num1, num2 = int(num1), int(num2)
        # 根据符号计算结果
        if operator == '*':
            result = num1 * num2
            print("识别出的数学表达式:", math_expression.group())
            print("计算结果:", result)
        elif operator == '+':
            result = num1 + num2
            print("识别出的数学表达式:", math_expression.group())
            print("计算结果:", result)
        else:
            result = "?"
            print("未能识别出数学表达式")
    else:
        result = "?"
        print("未能识别出数学表达式")

    # 等待验证码输入框出现并输入验证码
    captcha_input = wait.until(EC.presence_of_element_located((By.ID, 'captcha')))
    captcha_input.send_keys(str(result))

    # 等待登录按钮出现并点击
    login_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="root"]/span/div[3]/div/div/div[1]/div/div/form/div[5]/button[1]')))
    login_button.click()

    time.sleep(5)
    # 获取登录后的界面标题并输出
    print("登录后的界面标题:", driver.title)

except TimeoutException:
    print("等待超时，请检查网络或页面加载情况。")
except NoSuchElementException as e:
    print("元素未找到:", e)
finally:
    time.sleep(100)